const path = require('path')
const qiniu = require('qiniu')
class UploadPlugin {
  constructor(options) {
    const { bucket, domain, accessKey, secretKey } = options
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
    const putPolicy = new qiniu.rs.PutPolicy({ scope: bucket })
    this.uploadToken = putPolicy.uploadToken(mac)
    const config = new qiniu.conf.Config()
    config.zone = qiniu.zone.Zone_z2
    this.formUploader = new qiniu.form_up.FormUploader(config)
    this.putExtra = new qiniu.form_up.PutExtra()
  }

  apply(compiler) {
    compiler.hooks.afterCompile.tapPromise('UploadPlugin', (compilation) => {
      const assets = compilation.assets || []
      const promises = []
      Object.keys(assets).forEach((filename) => {
        console.log('----', filename);
        promises.push(this.upload(filename))
      })
      return Promise.all(promises)
    })
  }

  upload(filename) {
    return new Promise((resolve, reject) => {
      const localFile = path.resolve(__dirname, '../dist/', filename)
      this.formUploader.putFile(
        this.uploadToken,
        filename,
        localFile,
        this.putExtra,
        (respErr, respBody, respInfo) => {
          if (respErr) {
            reject(respErr)
          }
          if (respInfo.statusCode == 200) {
            console.log('上传成功', respBody);
            resolve(respBody)
          }
        }
      )
    })
  }
}

module.exports = UploadPlugin
